<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { reactive, unref, h, ref } from 'vue'
import { ElTag } from 'element-plus'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { useTable } from '@/hooks/web/useTable'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import BasicManageApi from '@/api/linePatrol/Basicmanage'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { Icon } from '@/components/Icon'
import { EventTypeListType } from '@/api/linePatrol/type'
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await BasicManageApi.GetEventTypeList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: res.data,
      total: res.data.length
    }
  },
  fetchDelApi: async () => {
    const res = await BasicManageApi.DeleEventType(unref(ids)[0])
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    type: 'selection',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'parentId',
    label: t('ID'),
    form: {
      component: 'Input',
      hidden: true,
      colProps: {
        span: 20
      },
      componentProps: {
        disabled: true
      }
    },
    detail: {
      hidden: true
    },
    table: { hidden: true }
  },
  {
    field: 'eventName',
    label: t('事件名称'),
    form: {
      hidden: false,
      colProps: {
        span: 20
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'eventCode',
    label: t('事件编码'),
    form: {
      hidden: false,
      colProps: {
        span: 20
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'status',
    label: t('事件状态'),
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(
        ElTag,
        {
          type: cellValue == 0 ? 'success' : 'danger'
        },
        () => (cellValue == 0 ? t('正常') : t('停用'))
      )
    },
    form: {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '正常',
            value: '0'
          },
          {
            label: '停用',
            value: '1'
          }
        ]
      },
      colProps: {
        span: 20
      }
    },
    detail: {
      span: 24,
      slots: {
        default: (data: any) => {
          if (data.status == 0) {
            return <span>正常</span>
          } else {
            return <span>停用</span>
          }
        }
      }
    }
  },
  {
    field: 'orderNum',
    label: t('排序'),
    form: {
      hidden: false,
      component: 'InputNumber',
      colProps: {
        span: 20
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    slots: {
      default: (data) => {
        return (
          <>
            <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
              {t('查看')}
            </span>
            <span class="TableBtn" onClick={() => action(data.row, 'add')}>
              {t('添加')}
            </span>
            <span class="TableBtn" onClick={() => action(data.row, 'edit')}>
              {t('修改')}
            </span>
            <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
              {t('删除')}
            </span>
          </>
        )
      }
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加')
const actionType = ref('')
const currentRow = ref<EventTypeListType | null>(null)
//表格操作
const action = (row: EventTypeListType, type: string) => {
  actionType.value = type
  dialogVisible.value = true
  if (type == 'add') {
    currentRow.value = { parentId: row.id }
    dialogTitle.value = '添加'
  } else if (type == 'edit') {
    dialogTitle.value = '修改'
    currentRow.value = row
  } else {
    dialogTitle.value = '详情'
    currentRow.value = row
  }
}
const delLoading = ref(false)
const ids = ref<string[]>([])
//删除轨迹
const delData = async (row: EventTypeListType) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const writeRef = ref()
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await BasicManageApi.AddEventType(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await BasicManageApi.EditEventType(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="13" />新增
    </BaseButton>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog style="width: 500px" v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'Detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <Detail
      v-if="actionType === 'Detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('提交') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
:deep(.TableBtn) {
  margin: 0 5px;
  font-size: 12px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600 !important;
}
</style>
